import 'package:flutter/material.dart';
import 'package:flutter_bilibili/mock/video_data.dart';
import 'package:flutter_bilibili/model/video_mo.dart';
import 'package:flutter_bilibili/util/color_util.dart';
import 'package:flutter_bilibili/widget/hi_banner.dart';
import 'package:flutter_bilibili/widget/keep_alive_wrapper.dart';
import 'package:flutter_bilibili/widget/video_card.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

class HomeTabPage extends StatefulWidget {
  final String name;

  const HomeTabPage({super.key, required this.name});

  @override
  State<HomeTabPage> createState() => _HomeTabPageState();
}

class _HomeTabPageState extends State<HomeTabPage> {
  ScrollController scrollController = ScrollController();
  bool loading = false;
  late List<VideoMo> videoList;

  @override
  void initState() {
    super.initState();
    videoList = videoData
        .map((item) => VideoMo.fromJson(item))
        .toList(); // videoData类型转换 json=>map
    scrollController.addListener(() {
      /// 计算滚动距离差
      var dis = scrollController.position.maxScrollExtent -
          scrollController.position.pixels;
      if (dis < 300 && !loading) {
        // todo: 给列表绑定scrollController，实现上拉加载
        // todo: 距离底部小于300时，加载更多
      }
    });
  }

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: () {
        // todo:预留口子，下拉刷新，重新请求数据
        return Future.delayed(const Duration(milliseconds: 1000), () {
          videoList.shuffle(); // 打乱list顺序
          setState(() {
            videoList = videoList;
          });
        });
      },
      color: primary,
      child: KeepAliveWrapper(
        child: SingleChildScrollView(
          child: Column(
            children: [
              if (widget.name == '推荐')
                const Padding(
                  padding: EdgeInsets.only(left: 10, right: 10, top: 10),
                  child: HiBanner(),
                ),
              Padding(
                padding: const EdgeInsets.only(left: 10, right: 10, top: 10),
                child: StaggeredGrid.count(
                  crossAxisCount: 4,
                  mainAxisSpacing: 4,
                  crossAxisSpacing: 4,
                  children: videoList.map((videoMo) {
                    return StaggeredGridTile.count(
                      crossAxisCellCount: 2,
                      mainAxisCellCount: 2,
                      child: VideoCard(videoMo: videoMo),
                    );
                  }).toList(),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
